package org.footballmanager.pandafootball.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.annotation.SystemServiceLog;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.system.domain.*;
import org.footballmanager.pandafootball.system.domain.enums.FL;
import org.footballmanager.pandafootball.system.domain.enums.ZDZT;
import org.footballmanager.pandafootball.system.domain.enums.ZDZW;
import org.footballmanager.pandafootball.system.form.impl.FootSociatySearchForm;
import org.footballmanager.pandafootball.system.mapper.FootSociatyMapper;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FootSociatyServiceImpl extends ServiceImpl<FootSociaty> implements FootSociatyService {
	@Autowired
	private FootSociatyMapper footSociatyMapper;
	@Autowired
	private FootSociatyInfoService footSociatyInfoService;
	@Autowired
	private FootTeamService footTeamService;
	@Autowired
	private FootUserService footUserService;
    @Autowired
    private PhotoService photoService;
    @Autowired
    private ImageUpload imageUploader;
    @Autowired
    private FootLevelUpService footLevelUpService;
    @Autowired
    private FootDanGradingService footDanGradingService;

	@Override
	@Transactional
	public boolean createSociaty(Long userId, String name, HttpServletRequest request){
		//首先要确保没有战队
		Example example = new Example(FootSociaty.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("name", name);
		FootSociaty fsold = this.findByExample(example);
		FootUser user = footUserService.get(userId);
		if(null == fsold && null == this.findFootSociatyByUserid(userId) && user != null && user.getJoins()){
			//花费100来创建战队
			FootTeam team = footTeamService.getTeamByUserid(userId);
			if(team != null){
				team.setQdZzj(team.getQdZzj() - 100D);
				footTeamService.updateNotNull(team, request);
			}
			FootSociaty fs = new FootSociaty();
			fs.setCreateTime(new Date());
			fs.setCreateId(userId);
			fs.setHaveNum(1);
			fs.setJf(0);
			fs.setLoseTime(0);
			fs.setSameTime(0);
			fs.setWinTime(0);
			fs.setTotalNum(3);
			fs.setName(name);
			this.save(fs, request);
			FootSociatyInfo fsi = new FootSociatyInfo();
			fsi.setZdId(fs.getId());
			fsi.setHonor(0L);
			fsi.setUserId(userId);
			fsi.setRelation(ZDZW.CDR);
			footSociatyInfoService.save(fsi, request);
			return true;
		}
		return false;
	}

	@Override
	public void deleteSociaty(Long userId, HttpServletRequest request){
		FootSociaty fs = this.findFootSociatyByUserid(userId);
		if(null != fs){
			List<FootSociatyInfo> users = footSociatyInfoService.findSociatyBySociatyId(fs.getId());
			if(null != users && !users.isEmpty()){
				for(FootSociatyInfo fsi: users){
					fsi.setZdId(null);
					fsi.setRelation(ZDZW.MEMBER);
					fsi.setHonor(0L);
					footSociatyInfoService.updateNotNull(fsi, request);
				}
			}
			this.delete(fs.getId(), request);
		}
	}

	@Override
	public FootSociaty findFootSociatyByUserid(Long userId) {
		Example example = new Example(FootSociatyInfo.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo(Constants.USERID, userId);
		FootSociatyInfo fsi = footSociatyInfoService.findByExample(example);
		if(fsi != null){
			return this.get(fsi.getZdId());
		}
		return null;
	}

	@Override
	public boolean addSociaty(Long userId, Long zdId, HttpServletRequest request){
		FootUser user = footUserService.get(userId);
		FootSociaty fs = this.get(zdId);
		FootSociaty fsy = this.findFootSociatyByUserid(userId);
		FootSociatyInfo fsi = footSociatyInfoService.findFootSociatyInfoByUserid(userId, request);
		List<FootSociatyInfo> footSociatyInfos = footSociatyInfoService.findSociatyBySociatyId(zdId);
		boolean result = processSociatyError(zdId, fs, fsy, fsi, user, footSociatyInfos);
		if(result){
			fs.setHaveNum(fs.getHaveNum() + 1);
			this.updateNotNull(fs, request);
			fsi.setZdId(zdId);
			footSociatyInfoService.updateNotNull(fsi, request);
		}
		return result;
	}

	private boolean processSociatyError(Long zdId, FootSociaty fs, FootSociaty fsy, FootSociatyInfo fsi,
										FootUser user, List<FootSociatyInfo> footSociatyInfos){
		boolean flag1 =  !(null == zdId || fs == null || null == footSociatyInfos || footSociatyInfos.isEmpty());
		boolean flag2 = fsy != null || fsi == null || user == null || !user.getJoins();
		return flag1 && flag2 && fs.getHaveNum() > footSociatyInfos.size();
	}

	@Override
	public boolean exitSociaty(Long userId, Long zdId, HttpServletRequest request){
		if(null != zdId){
			FootSociaty fs = this.get(zdId);
			if(fs != null && footSociatyInfoService.exitSociaty(userId, request)){
				fs.setHaveNum(fs.getHaveNum() - 1);
				this.updateNotNull(fs, request);
				return true;
			}
		}
		return false;
	}

	@Override
	public void changeStatus(boolean status, HttpServletRequest request) {
		List<FootSociaty> list = this.getall();
		if(null != list && !list.isEmpty()){
			for(FootSociaty fs: list){
				if(status){
					fs.setStatus(ZDZT.ENABLED);
				}else{
					fs.setStatus(ZDZT.CLOSE);
				}
				this.updateNotNull(fs, request);
			}
		}
	}

    /**
     * 保存战队记录
     * @param entity 实体类
     * @param img 上传文件
     *@param request 请求
     */
    @Override
    @Transactional
    @SystemServiceLog(description = "保存战队记录")
    public void save(FootSociaty entity, MultipartFile img, HttpServletRequest request){
        Photo photo = new Photo();
        photo.setImg(entity.getImg());
        photoService.processPhoto(photo, img);
        photo.setUrl(imageUploader.addPhoto(img, request, FL.WINGS));
        photoService.save(photo, request);
        super.save(entity, request);
    }

    @Override
    @Transactional
    @SystemServiceLog(description = "更新战队记录")
    public void update(FootSociaty entity, MultipartFile img, HttpServletRequest request) {
        Photo photo = new Photo();
        photo.setImg(entity.getImg());
        photoService.processPhoto(photo, img);
        photo.setUrl(imageUploader.upload(img, request, FL.WINGS));
        photoService.updateNotNull(photo, request);
        super.updateNotNull(entity, request);
    }

    /**
     * 报分确认后更新数据
     * @param bf 报分实体类
     * @param request 请求
     */
    @Override
    public void addEncourage(FootSociatyBfinfo bf, HttpServletRequest request) {
        FootSociaty zhufc = this.get(bf.getZd1());
        FootSociaty kefc = this.get(bf.getZd2());
        //战队排行数据更新
        if(zhufc != null && kefc != null){
            if(bf.getJq1() > bf.getJq2()){
                //2代表主队胜利,1代表平,0代表主队负
                zhufc.setJf(zhufc.getJf() + 3);
                zhufc.setWinTime(zhufc.getWinTime() + 1);
                kefc.setLoseTime(kefc.getLoseTime() + 1);
            }else if(bf.getJq1().equals(bf.getJq2())){
                zhufc.setJf(zhufc.getJf() + 1);
                zhufc.setSameTime(zhufc.getSameTime() + 1);
                kefc.setJf(kefc.getJf() + 1);
                kefc.setSameTime(kefc.getSameTime() + 1);
            }else{
                zhufc.setLoseTime(zhufc.getLoseTime() + 1);
                kefc.setJf(kefc.getJf() + 3);
                kefc.setWinTime(kefc.getWinTime() + 1);
            }
        }
        this.updateNotNull(zhufc, request);
        this.updateNotNull(kefc, request);
        this.reComputeRank(zhufc, kefc, request);
    }

    /**
     * 删除报分后更新数据
     *
     * @param bf       报分实体类
     * @param request 请求
     */
    @Override
    public void deleteEncourage(FootSociatyBfinfo bf, HttpServletRequest request) {
        FootSociaty zhufc = this.get(bf.getZd1());
        FootSociaty kefc = this.get(bf.getZd2());
        //战队排行数据更新
        if(zhufc != null && kefc != null){
            if(bf.getJq1() > bf.getJq2()){
                //2代表主队胜利,1代表平,0代表主队负
                zhufc.setJf(zhufc.getJf() - 3);
                zhufc.setWinTime(zhufc.getWinTime() - 1);
                kefc.setLoseTime(kefc.getLoseTime() - 1);
            }else if(bf.getJq1().equals(bf.getJq2())){
                zhufc.setSameTime(zhufc.getSameTime() - 1);
                zhufc.setJf(zhufc.getJf() - 1);
                kefc.setJf(kefc.getJf() - 1);
                kefc.setSameTime(kefc.getSameTime() - 1);
            }else{
                zhufc.setLoseTime(zhufc.getLoseTime() - 1);
                kefc.setJf(kefc.getJf() - 3);
                kefc.setWinTime(kefc.getWinTime() - 1);
            }
        }
        this.updateNotNull(zhufc, request);
        this.updateNotNull(kefc, request);
        this.reComputeRank(zhufc, kefc, request);
    }

    /**
     * 重新计算战队情况
     *
     * @param zhufc 主球队
     * @param kefc 客球队
     * @param request 请求
     */
    @Override
    public void reComputeRank(FootSociaty zhufc, FootSociaty kefc, HttpServletRequest request) {
        FootLevelUp zhuFootLevelUp = footLevelUpService.calculateLevel(zhufc, request);
        FootLevelUp keFootLevelUp = footLevelUpService.calculateLevel(kefc, request);
        zhufc.setLevel(zhuFootLevelUp.getLevel());
        zhufc.setLiveness(zhufc.getLiveness() + 50);
        zhufc.setDanGradingId(zhuFootLevelUp.getDanGradingId());
        kefc.setLevel(keFootLevelUp.getLevel());
        kefc.setLiveness(kefc.getLiveness() + 50);
        kefc.setDanGradingId(keFootLevelUp.getDanGradingId());
        this.updateNotNull(zhufc, request);
        this.updateNotNull(kefc, request);
    }

    /**
     * 查询
     *
     * @param footSociatySearchForm 条件
     * @return 列表
     */
    @Override
    public List<FootSociaty> findall(FootSociatySearchForm footSociatySearchForm) {
        return footSociatyMapper.findall(footSociatySearchForm);
    }

    @Override
    public FootSociaty get(Serializable id){
        return footSociatyMapper.findById(id);
    }

    /**
     * 查询
     *
     * @param entityname            实体类名
     * @param map                   参数
     * @param footSociatySearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootSociatySearchForm footSociatySearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footSociatySearchForm);
        Page<FootSociaty> page = PageHelper.startPage(footSociatySearchForm.getPageIndex(), footSociatySearchForm.getPageSize());
        List<FootSociaty> list = this.findall(footSociatySearchForm);
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }

    /**
     * 删除所有
     *
     * @param footSociatySearchForm 条件
     * @param request               请求
     */
    @Override
    public void deleteAll(FootSociatySearchForm footSociatySearchForm, HttpServletRequest request) {
        if(footSociatySearchForm.getSelectIds() != null){
            String[] result = footSociatySearchForm.getSelectIds().split(Constants.COMMA);
            for(String id: result){
                this .delete(Long.parseLong(id), request);
            }
        }
    }
}
